package com.xdja.netty.handler.inbound;

import com.xdja.netty.conf.HttpManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * description
 *
 * @author zk
 * @since 2018/7/24
 */
public class HttpCombinationDecoder extends ChannelInboundHandlerAdapter {
    /**
     * static logger
     */
    private static Logger logger = LoggerFactory.getLogger(HttpCombinationDecoder.class);
    
    /**
     * 共有entry,用来构建一个完整的http
     */
    private volatile static HttpManager.Entry<HttpRequest, HttpContent> requestHttpContentEntry = new HttpManager.Entry<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            putHttpRequest((HttpRequest) msg);
        } else if (msg instanceof HttpContent) {
            HttpManager.Entry<HttpRequest,HttpContent> willUsedEntry = putHttpContent((HttpContent) msg);
            ctx.fireChannelRead(willUsedEntry);
        }
    }

    /**
     * 存放request
     *
     * @param httpRequest request
     */
    public static void putHttpRequest(HttpRequest httpRequest) {
        requestHttpContentEntry.clearMe();
        requestHttpContentEntry.setHttpRequest(httpRequest);
    }

    /**
     * 存放httpContent
     *
     * @param content content
     */
    public static HttpManager.Entry<HttpRequest,HttpContent> putHttpContent(HttpContent content) {
        if (requestHttpContentEntry.getHttpRequest() == null) {
            logger.warn("this content is will skip");
            return null;
        }
        requestHttpContentEntry.setHttpContent(content);

        //url -> entry
//        String url = getRealUrl(requestHttpContentEntry.getHttpRequest().uri());

        //unAddUrl
//        if(UnAddUrl.isUnAdd(url)){
//            return requestHttpContentEntry.copyMe();
//        }

//        httpRequestMapping.put(url,requestHttpContentEntry.copyMe());
        return requestHttpContentEntry.copyMe();
    }

}
